import { getDB } from '../../db';

/**
 * 数据存储与管理  列表+条件查询
 */
export const getVideoRecordingtStatement = (queryParams: LX.DBService.DataStorageVideoInfoQuery) => {
  const db = getDB();
  let query = `
      SELECT "id", "video_name", "video_duration", "file_size", "start_time", "end_time", "channel", "status", "download_status", "save_path", "create_time", "create_user" 
      FROM "main"."video_info" WHERE "status" = 0 
    `;

  const conditions: string[] = [];
  const params: any = {};

  if (queryParams.videoName !== undefined) {
    conditions.push('video_name LIKE @videoName');
    params['videoName'] = `%${queryParams.videoName}%`;
  }

  if (queryParams.startTime) {
    conditions.push(`"create_time" >= @startTime`);
    params['startTime'] = queryParams.startTime;
  }
  if (queryParams.endTime) {
    conditions.push(`"create_time" <= @endTime`);
    params['endTime'] = queryParams.endTime;
  }

  if (conditions.length > 0) {
    query += ' AND ' + conditions.join(' AND ');
  }

  query += ' ORDER BY "create_time" DESC';

  if (queryParams.current !== undefined && queryParams.page !== undefined) {
    query += ' LIMIT @current, @page';
    params['current'] = queryParams.current;
    params['page'] = queryParams.page;
  }
  return db.prepare(query).all(params);
};

/**
 * 数据存储与管理  列表总条数+条件查询
 */
export const getVideoRecordingCounttStatement = (queryParams: LX.DBService.DataStorageVideoInfoQuery) => {
  const db = getDB();
  let query = `
      SELECT count(id) as count FROM "main"."video_info" WHERE "status" = 0
    `;

  const conditions: string[] = [];
  const params: any = {};

  if (queryParams.videoName !== undefined) {
    conditions.push('video_name LIKE @videoName');
    params['videoName'] = `%${queryParams.videoName}%`;
  }

  if (queryParams.startTime) {
    conditions.push(`"create_time" >= @startTime`);
    params['startTime'] = queryParams.startTime;
  }
  if (queryParams.endTime) {
    conditions.push(`"create_time" <= @endTime`);
    params['endTime'] = queryParams.endTime;
  }

  if (conditions.length > 0) {
    query += ' AND ' + conditions.join(' AND ');
  }

  return db.prepare(query).get(params);
};
